from django.shortcuts import render
from rest_framework import viewsets
from rest_framework import status
from rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly
from rest_framework.decorators import action
from rest_framework.response import Response
from .models import *
from .serializers import *
from apps.system.serializers import UserSerializer
from .filters import *
from .handles import get_kube_deployment_info
# Create your views here.


class KubernetesViewSet(viewsets.ModelViewSet):
    queryset = Kubernetes.objects.all()
    serializer_class = KubernetesSerializer
    permission_classes = [IsAuthenticated]
    filter_class = KubenetesFilter

    @action(methods=['get'], detail=True)
    def deployment(self, request, pk, *args, **kwargs):

        namespace = request.GET.get('namespace')
        if not namespace:
            return Response({'code': 10000, 'message': '缺少参数namespace'})
        object = self.get_object()
        data = get_kube_deployment_info(object.id, object.kubeconfig, namespace)
        return Response({'code': 20000, 'data': data})



class DockerRepoViewSet(viewsets.ModelViewSet):
    queryset = DockerRepo.objects.all()
    serializer_class = DockerRepoSerializer
    permission_classes = [IsAuthenticated]
    filter_class = DockerRepoFilter


class BusinessViewSet(viewsets.ModelViewSet):
    queryset = Business.objects.all()
    serializer_class = BusinessSerializer
    permission_classes = [IsAuthenticated]
    filter_class = BusinessFilter


    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        if instance.projects.count():
            msg = "存在关联项目，请先删除{}".format(','.join([p.code for p in instance.projects.all()]))
            return Response({'code': 10000, 'msg': msg}, status=status.HTTP_200_OK)
        self.perform_destroy(instance)
        return Response(status=status.HTTP_204_NO_CONTENT)

    def get_queryset(self):
        query = super(BusinessViewSet,self).get_queryset()
        user = self.request.user
        if user.is_superuser:
            return query
        ids = LobPerm.objects.filter(user=user).values_list('business_id', flat=True)
        query = query.filter(id__in=ids)
        return query


    @action(methods=['get'], detail=False)
    def select(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = BusinessSelectSerializer(queryset, many=True)
        return Response({'code': 20000, 'data': serializer.data})

    @action(methods=['get'], detail=True)
    def userselect(self, request, pk=None):
        object = self.get_object()
        perms = object.perms.filter(business=pk).values_list('user', flat=True)
        users = User.objects.exclude(id__in=perms)
        serializer = UserSerializer(users, many=True)
        return Response({'code': 20000, 'data': serializer.data})

    @action(methods=['get'], detail=True)
    def perms(self, request, pk):
        queryset = LobPerm.objects.filter(business=self.get_object(), project__isnull=True, service__isnull=True)
        serializer = LobPermSerializer(queryset, many=True)
        return Response({'code': 20000, 'data': serializer.data})


class ProjectViewSet(viewsets.ModelViewSet):
    queryset = Project.objects.all()
    serializer_class = ProjectSerializer
    permission_classes = [IsAuthenticated]
    filter_class = ProjectFilter



    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        if instance.services.count():
            msg = "存在关联服务，请先删除{}".format(','.join([s.code for s in instance.services.all()]))
            return Response({'code': 10000, 'msg': msg}, status=status.HTTP_200_OK)
        self.perform_destroy(instance)
        return Response(status=status.HTTP_204_NO_CONTENT)

    @action(methods=['get'], detail=False)
    def select(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = ProjectSelectSerializer(queryset, many=True)
        return Response({'code': 20000, 'data': serializer.data})

class ServiceViewSet(viewsets.ModelViewSet):
    queryset = Service.objects.all()
    serializer_class = ServiceSerializer
    permission_classes = [IsAuthenticated]
    filter_class = ServiceFilter
    ordering = ('id', )

    @action(methods=['get'], detail=False)
    def select(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = ServiceSelectSerializer(queryset, many=True)
        return Response({'code': 20000, 'data': serializer.data})

class EnvironmentViewSet(viewsets.ModelViewSet):
    queryset = Environment.objects.all()
    serializer_class = EnvironmentSerializer
    permission_classes = [IsAuthenticated]
    filter_class = EnvironmentFilter


class LobPermViewSet(viewsets.ModelViewSet):
    queryset = LobPerm.objects.all()
    serializer_class = LobPermSerializer
    permission_classes = [IsAuthenticated]
    filter_class = LobPermFilter

